package com.haojiang.mh.remote.ui.frag

import android.text.TextUtils
import android.view.MenuItem
import android.widget.Toolbar
import com.haojiang.mh.R
import com.haojiang.mh.remote.adapter.GroupExpandableListViewAdapter
import com.haojiang.mh.remote.base.BaseFrag
import com.haojiang.mh.remote.bean.BleRssiDevice
import com.haojiang.mh.remote.bean.ControlLeftMenuBean
import com.haojiang.mh.remote.bean.DeviceModifySuccessEvent
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.enums.EStep
import com.haojiang.mh.remote.event.*
import com.haojiang.mh.remote.ui.dialog.BleGroupDialogFrag
import com.haojiang.mh.remote.ui.dialog.SelecBedDialogFrag
import com.haojiang.mh.remote.ui.dialog.SelectGroupDialogFrag
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.BleUtil.Companion.connectMap
import com.haojiang.mh.remote.utils.BleUtil.Companion.lastConnect
import com.haojiang.mh.remote.utils.BleUtil.Companion.prepareConnect
import com.haojiang.mh.remote.utils.BleUtil.Companion.readGroupSurfaceNo
import com.haojiang.mh.remote.utils.Constant
import com.haojiang.mh.remote.utils.Util
import com.haojiang.mh.remote.view.IHomeFragViewCallback
import com.lx.permission.IPermissionCallback
import com.lx.permission.PermissionManager
import kotlinx.android.synthetic.main.frag_group.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
import kotlin.collections.ArrayList


class GroupFrag : BaseFrag(), IHomeFragViewCallback {

    private var itemAdd: MenuItem? = null
    val groupExpandableListViewAdapter by lazy { GroupExpandableListViewAdapter(activity, expandableListView) }
//    val groupExpandableListViewAdapter = GroupExpandableListViewAdapter(expandableListView)

    private val mIPermissionCallback = IPermissionCallback {
//        startActivity(Intent(activity, GuideActivity::class.java))
    }

    private fun callInterface() {
        if (!Util.checkBleStatus(activity!!)) return
        //申请权限
        PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback, 0)
        PermissionManager.getInstance().requestPermission(
            activity!!,
            BleUtil.permissionArr
        )
    }

    override fun onLayoutId(): Int {
        return R.layout.frag_group
    }

    override fun initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
//        return View.inflate(context, R.layout.frag_group, null)
    }

    override fun initListener() {
        setHasOptionsMenu(true);

        groupToolbar.inflateMenu(R.menu.toolbar_group)
        groupToolbar.setOnMenuItemClickListener(object : Toolbar.OnMenuItemClickListener, androidx.appcompat.widget.Toolbar.OnMenuItemClickListener {
            override fun onMenuItemClick(item: MenuItem?): Boolean {
                when (item!!.itemId) {
                    android.R.id.home -> {
                        EventBus.getDefault().post(DrawerEvent())
                    }

                    R.id.itemAdd -> {
                        callInterface()
                    }

                    R.id.itemDelete -> {
                        groupExpandableListViewAdapter.delete(context)
                    }
                }
                return true
            }
        })

//        (activity as AppCompatActivity?)?.setSupportActionBar(groupToolbar)
//        (activity as AppCompatActivity?)?.supportActionBar?.let {
//            it.setDisplayHomeAsUpEnabled(true)
//            it.setHomeAsUpIndicator(R.drawable.ic_menu)
////            it.title = ""
//        }
        expandableListView.setAdapter(groupExpandableListViewAdapter)
        groupExpandableListViewAdapter.setData(connectMap)
    }

    override fun initData() {
//        LogUtil.e("组界面初始化完毕")
    }

//    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
//        inflater.inflate(R.menu.toolbar_group, menu)
//        itemAdd = menu.findItem(R.id.itemAdd)
//    }

//    override fun onOptionsItemSelected(item: MenuItem): Boolean {
//        when (item.itemId) {
//            android.R.id.home -> {
//                EventBus.getDefault().post(DrawerEvent())
//            }
//
//            R.id.itemAdd -> {
//                callInterface()
//            }
//
//            R.id.itemDelete -> {
//                groupExpandableListViewAdapter.delete(context)
//            }
//        }
//        return true
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun onGroupModifyEvent(event: GroupModifyEvent) {
//        if (event.className.equals(GroupFrag::class.java.simpleName)) {
//            activity?.run {
//                ModifyDialogFrag.show(
//                    activity!!,
//                    event.className,
//                    event.bleRssiDevice.bleAddress,
//                    event.bleRssiDevice.bleName,
//                    event.bleRssiDevice.deviceAlias!!
//                )
//            }
//        }else if (event.className.equals(BleGroupDialogFragAdapter::class.java.simpleName)){
//            activity?.run {
//                ModifyDialogFrag.show(
//                    activity!!,
//                    event.className,
//                    event.bleRssiDevice.bleAddress,
//                    event.bleRssiDevice.bleName,
//                    event.bleRssiDevice.deviceAlias!!
//                )
//            }
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDeviceModifySuccessEvent(event: DeviceModifySuccessEvent) {
//        if (event.className.equals(GroupFrag::class.java.simpleName)) {
        groupExpandableListViewAdapter.modifyItem(event.bleAddress, event.deviceAlias)
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAddGroupEvent(event: AddGroupEvent) {
        groupExpandableListViewAdapter.setData(connectMap)        //更新组列表
//            EventBus.getDefault().post(GroupConnectEvent())
//            SelectDialogFrag.show(activity!!, groupId = event.groupId)
//        SelectDialogFrag.show(activity!!, event.groupType, event.groupId)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onShowBleEvent(event: ShowBleEvent) {
//        BleDialogFrag.show(activity!!, event.groupType, event.groupId)
        BleGroupDialogFrag.show(activity!!, event.groupType, event.groupId)     //显示并搜索蓝牙
    }

    //组设备确定连接
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGroupConnectEvent(event: ConnectEvent) {
        if (event.connectType != EConnect.CONNECT_SINGLE.data) {
            if (event.connectStep == EStep.STEP_CLICK_CONNECT.data) {           //从点击组连接或者GroupTypeDialogFrag新建组Id并起名的界面过来列表为空，下一步准备选择设备列表
                BleGroupDialogFrag.show(activity!!, event.connectType, event.connectId)     //提示选择子选项
            } else if (event.connectStep == EStep.STEP_SELECT_DEVICE.data) {    //从BleGroupDialogFrag过来，已经选择好了设备列表下一步准备连接
                event.bleDeviceList?.run {
                    prepareConnect(event.bleDeviceList, event.connectType, event.connectId)                 //准备连接
                    connectDeviceList(event.connectType, event.connectId)
                }
            } else if (event.connectStep == EStep.STEP_SELECT_INTERFACE.data) {    //从SelectGroupDialogFrag或者SelecBedDialogFrag过来，已经选择好了设备列表下一步准备连接
                connectDeviceList(event.connectType, event.connectId)
            }
        }
    }

    private fun connectDeviceList(groupType: Int, groupId: Long) {
        val surfaceNo = readGroupSurfaceNo(groupId)                                                       //尝试读取界面，第一次连接没有界面
        if (TextUtils.isEmpty(surfaceNo)) {
            choiceSelectGroupFrag(groupType, groupId)                                   //第一次连接显示选择界面编号
            return
        }
        //获取_6BRM对应的功能 例如 HEAD_UP = 0x24
//        val funList = SurfaceKey.keyMap.get(interfaceNo.substring(0, 4).toUpperCase(Locale.ROOT))
//        if (funList != null && !interfaceNo.equals(Constant.QRRM, ignoreCase = true)) {
        val surface = BleUtil.getSurface(surfaceNo)
        if (surface != null && !surfaceNo.equals(Constant.QRRM, ignoreCase = true)) {
            val bleDeviceList = ArrayList<BleRssiDevice>()
            for ((key, value) in connectMap) {
                if (value.connectKey.id == groupId) {
                    value.connectValueList.forEach {
                        bleDeviceList.add(it.bleRssiDevice)
                    }
                    break
                }
            }
            groupExpandableListViewAdapter.setData(connectMap)
            lastConnect.bleDeviceList.clear()
            lastConnect.bleDeviceList.addAll(bleDeviceList)
            BleUtil.devConnects(lastConnect.bleDeviceList)   //连接蓝牙设备
            EventBus.getDefault().post(SurfaceEvent(surface))
        } else {
            choiceSelectGroupFrag(groupType, groupId)
        }
    }

    private fun choiceSelectGroupFrag(groupType: Int, groupId: Long) {
        when (Util.getPackageName()) {
            "com.richmat.richmat" -> {
                SelectGroupDialogFrag.show(activity!!, groupType, groupId)
            }
            "com.richmat.poshlavish" -> {
                SelecBedDialogFrag.show(activity!!, groupType, groupId)
            }
        }
    }


    override fun initDestroy() {
        EventBus.getDefault().unregister(this)
    }


    override fun onLoadSuccess(list: List<ControlLeftMenuBean>?) {

    }


    override fun onLoadError(message: String?) {

    }

    override fun onLoadMore(list: List<ControlLeftMenuBean>?) {

    }

}


//        val groupKey1 = GroupKey("组一")
//        val groupValueList1 = ArrayList<GroupValue>()
//        groupValueList1.add(GroupValue("A8-1E-84-B0-A1-65", "设备1"))
//        groupValueList1.add(GroupValue("A8-1E-84-B0-A1-66", "设备2"))
//        val bleGroup1 = BleGroup(groupKey1, groupValueList1)
//
//        val groupKey2 = GroupKey("组二")
//        val groupValueList2 = ArrayList<GroupValue>()
//        groupValueList2.add(GroupValue("A9-1E-84-B0-A1-67", "设备3"))
//        groupValueList2.add(GroupValue("A9-1E-84-B0-A1-68", "设备4"))
//        val bleGroup2 = BleGroup(groupKey2, groupValueList2)
//
//        val groupKey3 = GroupKey("组三")
//        val groupValueList3 = ArrayList<GroupValue>()
//        groupValueList3.add(GroupValue("A9-1E-84-B0-A1-67", "设备5"))
//        groupValueList3.add(GroupValue("A9-1E-84-B0-A1-68", "设备6"))
//        val bleGroup3 = BleGroup(groupKey3, groupValueList3)
//
//        val groupKey4 = GroupKey("组四")
//        val groupValueList4 = ArrayList<GroupValue>()
//        groupValueList4.add(GroupValue("A9-1E-84-B0-A1-67", "设备7"))
//        groupValueList4.add(GroupValue("A9-1E-84-B0-A1-68", "设备8"))
//        groupValueList4.add(GroupValue("A9-1E-84-B0-A1-68", "设备9"))
//        val bleGroup4 = BleGroup(groupKey4, groupValueList4)
//
//        val groupKey5 = GroupKey("组五")
//        val groupValueList5 = ArrayList<GroupValue>()
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-67", "设备10"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备11"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备12"))
//        groupValueList5.add(GroupValue("A9-1E-84-B0-A1-68", "设备20"))
//        val bleGroup5 = BleGroup(groupKey5, groupValueList5)
//
//        bleGroupMap.put("组一key", bleGroup1)
//        bleGroupMap.put("组二key", bleGroup2)
//        bleGroupMap.put("组三key", bleGroup3)
//        bleGroupMap.put("组四key", bleGroup4)
//        bleGroupMap.put("组五key", bleGroup5)
//
//        groupExpandableListViewAdapter.setData(bleGroupMap)
//
//        expandableListView.setAdapter(groupExpandableListViewAdapter)
//    }
//
//    fun onClick(view: View) {
////        when (view.id) {
////            R.id.btn1 -> {
//        val map = LinkedHashMap<String, BleGroup>()
//        val groupKey1 = GroupKey("组一")
//        val groupValueList1 = ArrayList<GroupValue>()
//        groupValueList1.add(GroupValue("A8-1E-84-B0-A1-65", "设备1"))
//        groupValueList1.add(GroupValue("A8-1E-84-B0-A1-66", "设备2"))
//        val bleGroup1 = BleGroup(groupKey1, groupValueList1)
//
//        val groupKey2 = GroupKey("组二")
//        val groupValueList2 = ArrayList<GroupValue>()
//        groupValueList2.add(GroupValue("A9-1E-84-B0-A1-67", "设备3"))
//        groupValueList2.add(GroupValue("A9-1E-84-B0-A1-68", "设备4"))
//        val bleGroup2 = BleGroup(groupKey2, groupValueList2)
//
//        map.put("组一key", bleGroup1)
//        map.put("组二key", bleGroup2)


//                if (SpUtil.putHashMapData(KEY_BLE_GROUP, map)) {
////                    Toast.makeText(this, "保存成功", 0).show()
//                }
//            }

//            R.id.btn2 -> {
//                val hashMapData = SpUtil.getHashMapData(KEY_BLE_GROUP, BleGroup::class.java)
//                if (hashMapData != null) {
////                    Toast.makeText(this, "读取成功", 0).show()
//
//                    hashMapData.forEach {
//                        Log.e("colin", it.key.toString() + "-------------" + it.value.toString())
//
//                        Log.e("colin", it.value.groupKey.toString())
//                        it.value.groupValueList.forEach {
//
//                            Log.e("colin", it.address + "---" + it.name)
//                        }
//                    }
//                }
//            }


//        }